<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
    <div style="padding-left: 12px;padding-right: 12px;padding-bottom: 12px;">
        <el-card :body-style="{ padding: '10px' }">
            <el-row style="margin: 1% 0% 1% 0%">
                <el-col :span="4" align="left">
                    <span style="font-size:14px; line-height: 26px; color: #747778">财报信息列表</span>
                </el-col>
            </el-row>

            <el-row>
                <el-col style="display:flex">
                    <el-button type="primary" icon="el-icon-refresh" size="small" @click="load(1, pageSize)">刷新
                    </el-button>
                    <el-button v-if="editable && !institutionCustomer && financeReportData.length > 0" type="primary"
                               icon="el-icon-tickets" size="small" @click="analysisReportData">财报分析
                    </el-button>
                    <div style="margin-left: 0.8%">
                        <el-upload
                                v-if="editable"
                                :http-request="uploadReport"
                                action="/joys-rest/lss-customer/financeReport/upload"
                                :headers="token"
                                :show-file-list="false"
                                ref="uploadFileRef"
                                width="100%">
                            <el-button type="primary" icon="el-icon-upload" size="small">导入</el-button>
                        </el-upload>
                    </div>
                    <span style="margin-left: 2%">
                        <el-button v-if="editable" type="text" style="padding: 0px;font-size: 12px" @click="downlandTemplate">
                            <u style='color: rgb(0, 98, 222);'>财报模版，点击此处下载</u>
                        </el-button>
                    </span>
                </el-col>
            </el-row>
            <div v-if="financeReportData.length > 0">
                <ft-pagination :total="totalElements" :current-page="currentPage" :page-size="pageSize"
                               @pageChange="load">
                    <el-table :data="financeReportData" ref="financeReportDataRef">
                        <el-table-column align='left' label="名称" prop="reportName">
                            <template slot-scope="scope">
                                <ft-link-text @click="showReportDialog(scope.row)"
                                              :text="scope.row.reportName">
                                </ft-link-text>
                            </template>
                        </el-table-column>
                        <el-table-column align='left' label="报表年份" prop="reportTerm"></el-table-column>
                        <el-table-column align='left' label="报表类型" prop="reportType">
                            <template slot-scope="scope">
                                <ft-enum-select v-model="scope.row.reportType"
                                                service-name="lss-customer"
                                                type-name="reportType"
                                                :editing="false">
                                </ft-enum-select>
                            </template>
                        </el-table-column>
                        <el-table-column align='left' label="报表类型细分" prop="reportDetailType">
                            <template slot-scope="scope">
                                <ft-enum-select v-model="scope.row.reportDetailType"
                                                service-name="lss-customer"
                                                type-name="reportDetailType"
                                                :editing="false">
                                </ft-enum-select>
                            </template>
                        </el-table-column>
                        <el-table-column align='left' label="报表状态" prop="confirmStatus">
                            <template slot-scope="scope">
                                <ft-enum-select v-model="scope.row.confirmStatus"
                                                service-name="lss-customer"
                                                type-name="confirmStatus"
                                                :editing="false">
                                </ft-enum-select>
                            </template>
                        </el-table-column>
                        <el-table-column align='left' label="导入时间" prop="creationTs">
                            <template slot-scope="scope">
                                <div>{{dateFormat(scope.row.creationTs)}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="editable" label="功能操作" width="200" align="center">
                            <template slot-scope="scope" v-if="scope.row.confirmStatus === 'UNCONFIRMED'">
                                <el-button size="small" type="text" @click="confirmReport(scope.row)">确认</el-button>
                                <el-popover title="" placement='top' width='200' v-model="scope.row.delVisible">
                                    <p>数据删除后，将不能恢复，确认删除？</p>
                                    <div style="text-align: right; margin: 0">
                                        <el-button size='small' @click="scope.row.delVisible=false">取消</el-button>
                                        <el-button type='danger' size='small' @click="handleDelete(scope.$index, scope.row)">确定</el-button>
                                    </div>
                                    <el-button slot="reference" type='text' size='small' style='color:#B94A48'>删除</el-button>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </el-table>
                </ft-pagination>

                <div v-if="showFinanceReportDialog">
                    <!--必须要有上面的v-if.来保证每次都可以重新加载这个组件,否则会出现错误-->
                    <finance-report-dialog ref="financeReportDialogRef"
                                           :dialog-title="showFinanceReportTitle"
                                           :report-detail-dialog="showFinanceReportDialog"
                                           :finance-report-id="showFinanceReportId"
                                           :editable="showFinanceReportConfirmStatus"
                                           @rentValue="rentValue">
                    </finance-report-dialog>
                </div>

            </div>
            <div v-else>
                <el-row style="justify-content: center">
                    <span style="padding-top: 25px">没有数据</span>
                </el-row>
            </div>

        </el-card>
        <br/>
        <div v-if="financeReportData.length > 0">
            <el-card :body-style="{ padding: '10px' }" v-show="showConfirmedTab">
                <div>
                    <finance-report-confirmed-tab :visible.sync="showConfirmedTab"
                                                  :customer-id="this.customerId"
                                                  ref="reportConfirmedTabRef">
                    </finance-report-confirmed-tab>
                </div>
            </el-card>
            <br/>
            <el-card :body-style="{ padding: '10px' }" v-show="!institutionCustomer && showAnalysisTab">
                <div>
                    <finance-report-analysis :visible.sync="showAnalysisTab"
                                             :customer-id="this.customerId"
                                             ref="reportAnalysisRef">
                    </finance-report-analysis>
                </div>
            </el-card>
        </div>


    </div>
</template>

<script>
    import FtDatePicker from '../ft/FtDatePicker'
    import FinanceReportConfirmedTab from './FinanceReportConfirmedTab'
    import FinanceReportDialog from './FinanceReportDialog'
    import FinanceReportAnalysis from './FinanceReportAnalysis'

    export default {
        name: 'FinanceReport',
        components: {
            'ft-date-picker': FtDatePicker,
            'finance-report-confirmed-tab': FinanceReportConfirmedTab,
            'finance-report-dialog': FinanceReportDialog,
            'finance-report-analysis': FinanceReportAnalysis
        },
        props: {
            customerId: {
                type : String,
                default : '',
            },
            editable: {
                type : Boolean,
                default : true,
            },
        },
        data() {
            return {
                currentPage: 1,
                pageSize: 8,
                totalElements: 0,
                // 财报信息
                financeReportData: [],
                // 是否展示财报具体信息dialog
                showFinanceReportDialog: false,
                // 展示的财报Id
                showFinanceReportId: '',
                // 展示dialog标题名称
                showFinanceReportTitle: '',
                // 展示的财报数据的确认状态
                showFinanceReportConfirmStatus: false,
                // 是否是事业单位客户
                institutionCustomer: true,
                // 是否展示财报确认信息组件
                showConfirmedTab: true,
                // 是否展示财报分析组件
                showAnalysisTab: true,


                token: {
                    "AUTH-TOKEN": localStorage.getItem("AUTH-TOKEN"),
                },
                upLoadData: {
                    fileId: "",
                    customerId: this.customerId,
                },
                // parentId: "34aafc0e-693f-48ee-81cb-a02a1ad5dc7d",
                // fileId: "",
                // fileName: "",
            }
        },
        mounted() {
            this.isInstitution()
            this.load()
        },
        watch: {},
        methods: {

            load(currentPage, pageSize) {
                // 更新当前页数和展示数据条数
                if (currentPage && currentPage !== '') {
                    this.currentPage = currentPage
                }
                if (pageSize && pageSize !== '') {
                    this.pageSize = pageSize
                }
                let params = {
                    customerId: this.customerId,
                    pageIndex: this.currentPage,
                    pageSize: this.pageSize,
                }
                const url = '/joys-rest/lss-customer/financeReport/customer/list'
                this.$http.post(url, '', {params}).then(
                    resp => {
                        this.totalElements = resp.body.total
                        this.financeReportData = resp.body.rows
                    }, resp => {
                        this.$message.error('财报基本数据加载失败, 请重试!')
                    }
                )
            },
            // 判断客户是否是事业单位客户
            isInstitution() {
                this.$http.get('/joys-rest/lss-customer/financeReport/institution/' + this.customerId).then(
                    resp => {
                        this.institutionCustomer = resp.body
                    }, resp => {
                        this.$message.error('获取客户组织机构类型失败,请重试')
                    }
                )
            },


            //确认财报数据
            confirmReport(row) {
                this.$confirm('请确保确认的该条数据是正确的, 确认该条数据后, 你将不能删除该条数据。', '提示信息', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const url = '/joys-rest/lss-customer/financeReport/confirm/'
                    this.$http.put(url + row.financeReportId).then(
                        resp => {
                            this.$message.success('确认成功')
                            // 刷新当前页面数据
                            this.load(this.currentPage, this.pageSize)
                            this.$refs.reportConfirmedTabRef.loadConfirmedReports()
                        }, resp => {
                            this.$message.error('确认当前财报失败，请重试')
                        }
                    )
                })
            },
            // 分析财报数据
            analysisReportData() {
                this.showAnalysisTab = true
                this.$refs.reportAnalysisRef.analysisReport()
            },
            //列表删除按钮
            handleDelete(index, row) {
                row.delVisible=false
                const url = '/joys-rest/lss-customer/financeReport/'
                this.$http.delete(url + row.financeReportId).then(
                    resp => {
                        // 刷新当前页面数据,
                        // 不在数组中直接删除该数据的原因：当删除数据后，为保持pageSize不变，需要加载下页一条数据，所以需要重新查询
                        this.load(this.currentPage, this.pageSize)
                        this.$message.success('删除成功')
                    }, resp => {
                        this.$message.error('删除失败,请重试')
                    }
                )
            },
            //上传财报
            uploadReport(item) {
                // 首先校验客户组织机构类型是否已维护,如果没有维护值,则提示先去维护组织机构类型
                let promise = new Promise(resolve => {
                    this.$http.get('/joys-rest/lss-customer/financeReport/enterprise/type/' + this.customerId).then(
                        resp => {
                            if (resp.bodyText) {
                                resolve()
                            } else {
                                this.$message.error('请先维护组织机构类型, 再导入财报!')
                            }
                        }, resp => {
                            this.$message.error(resp.body)
                        }
                    )
                })

                promise.then(
                    resolve => {
                        const url = '/joys-rest/lss-customer/financeReport/upload'
                        // FormData对象用以将数据编译成键值对,其主要用于发送表单数据，
                        // 但亦可用于发送带键数据(keyed data)，而独立于表单使用
                        let formData = new FormData();
                        formData.append('file', item.file)
                        formData.append('fileId', '') //需要上传附件时再补充
                        formData.append('customerId', this.customerId)
                        this.$http.post(url, formData, {headers: {'Content-Type': 'multipart/form-data'}}).then(
                            resp => {
                                // 向数组头添加元素,拼装成一个新的数组
                                this.financeReportData = resp.body.concat(this.financeReportData)
                                // 更新数据总数
                                this.totalElements = this.totalElements + resp.body.length
                                // 当前页面只展示pageSize个数据,如果多了就截取pageSize个
                                if (this.financeReportData.length > this.pageSize) {
                                    this.financeReportData.length = this.pageSize
                                }
                                this.$message.success("导入成功")
                            }, resp => {
                                this.$message.error(resp.body)
                            }
                        )
                    }
                )
            },


            rentValue() {
                this.$nextTick(() => {
                    this.showFinanceReportDialog = false
                })
            },

            //单击财报显示
            showReportDialog(row) {
                this.showFinanceReportConfirmStatus = row.confirmStatus === 'UNCONFIRMED'
                this.showFinanceReportId = row.financeReportId
                this.showFinanceReportTitle = row.reportTerm + '  ' + row.reportName
                this.showFinanceReportDialog = true

            },
            //日期格式化：yyyy-MM-dd HH:mm:ss
            dateFormat(value) {
                if (value == null || value == "") {
                    return
                } else {
                    let date = new Date(value)
                    return date.getFullYear() + '-' + this.cover(date.getMonth() + 1) + '-'
                        + this.cover(date.getDate()) + ' ' + this.cover(date.getHours()) + ':'
                        + this.cover(date.getMinutes()) + ':' + this.cover(date.getSeconds())
                }
            },
            cover(value) {
                if (value.toString().length === 1) {
                    value = "0" + value
                }
                return value
            },

            downlandTemplate() {
                let promise = new Promise(resolve => {
                    this.$http.get('/joys-rest/lss-customer/financeReport/enterprise/type/' + this.customerId).then(
                        resp => {
                            if (resp.bodyText) {
                                resolve()
                            } else {
                                this.$message.error('请先维护组织机构类型, 再下载财报模板!')
                            }
                        }, resp => {
                            this.$message.error(resp.body)
                        }
                    )
                })

                promise.then(
                    resolve => {
                        const url = '/joys-rest/lss-customer/financeReport/template/' + this.customerId + "?AUTH-TOKEN=" + localStorage.getItem('AUTH-TOKEN')
                        window.open(url)
                    }
                )

            }

        }
    }
</script>
<style>
    .upload-demo .el-upload-dragger {
        border: 0px;
        min-width: 600px;
    }
</style>
<style scoped>

</style>
